package com.chagee.store.operation.server.service.biz;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chagee.base.utils.*;
import com.chagee.store.operation.api.bo.AppealExtraVO;
import com.chagee.store.operation.api.bo.OrderExtJsonBO;
import com.chagee.store.operation.api.enums.*;
import com.chagee.store.operation.api.response.vo.AiResultVO;
import com.chagee.store.operation.api.request.OrderAppealRequest;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.common.constant.SupplierWorkOrderConstant;
import com.chagee.store.operation.common.enums.LarkMessageTypeEnum;
import com.chagee.store.operation.common.exception.BizErrorCode;
import com.chagee.store.operation.common.exception.BizException;
import com.chagee.store.operation.common.utils.ResponseUtil;
import com.chagee.store.operation.server.config.StoreOrderDeviceConfig;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.dao.WorkOrderReceiverMapper;
import com.chagee.store.operation.server.event.service.*;
import com.chagee.store.operation.server.model.bo.OrderAppealRecordBO;
import com.chagee.store.operation.server.model.info.LarkMessageInfo;
import com.chagee.store.operation.server.model.param.*;
import com.chagee.store.operation.server.model.response.SupplierTaskDetailResponse;
import com.chagee.store.operation.server.model.vo.*;
import com.chagee.store.operation.server.mq.WorkOrderExpiredTaskMqProduct;
import com.chagee.store.operation.server.service.StoreAppSweepService;
import com.chagee.store.operation.server.service.base.StoreBaseService;
import com.chagee.store.operation.server.service.base.SupplierWorkOrderBaseService;
import com.chagee.store.operation.server.service.base.WorkOrderDeviceBaseService;
import com.chagee.store.operation.server.service.third.FeiShuSendService;
import com.chagee.store.operation.server.utils.DateUtil;
import com.chagee.storeManagement.api.event.bo.EndOrderAndTaskAppealEventBizDataBO;
import com.chagee.storeManagement.api.event.enums.EventTypeEnum;
import com.chagee.storeManagement.api.event.request.OperateRecordRequest;
import com.chagee.storeManagement.api.event.request.TimerEventRegisterDefaultRequest;
import com.chagee.storeManagement.api.event.service.IEventApi;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.ObjectUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName SupplierWorkOrderBizService  //类名称
 * @Description: //类描述
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/04/25 13:53	//创建时间
 * @UpdateUser: Jacky-zhan	//作者
 * @UpdateDate: 2024/04/25 13:53	//更新时间
 * @UpdateRemark: 更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SupplierWorkOrderBizService extends ServiceImpl<WorkOrderReceiverMapper, WorkOrderReceiverDO> {

	@Resource
	private SupplierWorkOrderBaseService supplierWorkOrderBaseService;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private StoreBaseService storeBaseService;

	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;

	@Resource
	private WorkOrderDeviceBaseService workOrderDeviceBaseService;

	@Resource
	private StoreOrderDeviceConfig storeOrderDeviceConfig;

	@Value("${appeals.hours:24}")
	private Long hours;

	@Resource
	private FeiShuMessageBizService feiShuMessageBizService;

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Resource
	private WorkOrderAIService workOrderAIService;

	@Value("${work-order.taskName:智能茶饮机}")
	private String taskName;
	@Value("${ai-result.unqualifiedDesc}")
	private String aiResultDesc;
	@Resource
	private StoreAppSweepService storeAppSweepService;

	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;

	@Resource
	private FeiShuSendService feiShuSendService;

	@Value("${orderExpire.hours:48}")
	private Long orderExpire;

	@Resource
	private StoreConfigurationBaseService storeConfigurationBaseService;

	@Resource
	private WorkOrderExpiredTaskMqProduct workOrderExpiredTaskMqProduct;

	@Value("${orderAppeal.expiredTime:86400}")
	private Integer expiredTime;

	@Resource
	private IEventApi iEventApi;

	@Resource
	private OperateRecordBizService operateRecordBizService;

	/**
	 * 分页查询信息
	 *
	 * @param queryParam 入参
	 * @return 分页返回
	 */
	public PaginationData<SupplierWorkOrderVO> queryList(PaginationRequest<SupplierWorkOrderQueryParam> queryParam) {
		Page<WorkOrderReceiverDO> page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize());
		Page<WorkOrderReceiverDO> takeawayPage = supplierWorkOrderBaseService.pageQueryList(queryParam.getQueryParameter(), page);
		if (CollectionUtils.isEmpty(takeawayPage.getRecords())) {
			return ResponseUtil.emptyResponse(queryParam, SupplierWorkOrderVO.class, takeawayPage.getTotal());
		}
		List<SupplierWorkOrderVO> results = takeawayPage.getRecords().stream().map(t -> {
			SupplierWorkOrderVO supplierWorkOrderVO = new SupplierWorkOrderVO();
			BeanUtils.copyProperties(t, supplierWorkOrderVO);
			//获取工单对应的接单人信息
			WorkOrderDO workOrderDO = workOrderBaseService.selectById(t.getWorkOrderId());
			if (Objects.nonNull(workOrderDO)) {
				supplierWorkOrderVO.setId(workOrderDO.getId());
				String receiverName = workOrderDO.getReceiver();
				String receiverMobile = workOrderDO.getReceiverMobile();
				if (receiverName.contains(SupplierWorkOrderConstant.COMMA) || receiverMobile.contains(SupplierWorkOrderConstant.COMMA)) {
					List<String> nameList = Arrays.asList(receiverName.split(SupplierWorkOrderConstant.COMMA));
					List<String> mobileList = Arrays.asList(receiverMobile.split(SupplierWorkOrderConstant.COMMA));
					String receiverData = "";
					for (int i = 0; i < nameList.size(); i++) {
						if (i < nameList.size() - 1) {
							receiverData = receiverData + nameList.get(i).concat(SupplierWorkOrderConstant.LEFT_BRACKET)
								.concat(mobileList.get(i)).concat(SupplierWorkOrderConstant.RIGHT_BRACKET).concat(SupplierWorkOrderConstant.COMMA);
						} else {
							receiverData = receiverData.concat(nameList.get(i).concat(SupplierWorkOrderConstant.LEFT_BRACKET)
								.concat(mobileList.get(i)).concat(SupplierWorkOrderConstant.RIGHT_BRACKET));
						}
					}
					supplierWorkOrderVO.setReceiverData(receiverData);
				} else {
					supplierWorkOrderVO.setReceiverData(receiverName.concat(SupplierWorkOrderConstant.LEFT_BRACKET)
						.concat(receiverMobile).concat(SupplierWorkOrderConstant.RIGHT_BRACKET));
				}
				//返回满意度（评分）
				if (StringUtils.isNotBlank(workOrderDO.getDocumentScore())) {
					supplierWorkOrderVO.setDocumentScore(workOrderDO.getDocumentScore());
				}
			}
			//处理枚举type->value
			if (Objects.nonNull(supplierWorkOrderVO.getDocumentType())) {
				supplierWorkOrderVO.setDocumentTypeValue(
					Objects.requireNonNull(OrderStatusEnum.getByType(supplierWorkOrderVO.getDocumentType())).getDesc());
			}
			if (Objects.nonNull(supplierWorkOrderVO.getDocumentStatus())) {
				supplierWorkOrderVO.setDocumentStatusValue(
					Objects.requireNonNull(StoreWorkOrderStatusEnum.getByType(supplierWorkOrderVO.getDocumentStatus())).getDesc());
			}
			supplierWorkOrderVO.setCreateTime(workOrderDO.getCreateTime());
			boolean orderExpiredFlag = false;
			if (Objects.nonNull(workOrderDO.getExpiredTime())) {
				//工单过期申述有效期 48小时
				orderExpiredFlag = DateUtil.getOrderExpiredDate(workOrderDO.getExpiredTime(), orderExpire);
			}
			if (StringUtils.isNotBlank(workOrderDO.getAppealResult()) && OrderAppealStatusEnum.N.getType().equals(workOrderDO.getAppealResult())) {
				orderExpiredFlag = false;
			}
			supplierWorkOrderVO.setOrderExpiredFlag(orderExpiredFlag);
			return supplierWorkOrderVO;
		}).collect(Collectors.toList());
		return ResponseUtil.commonResponse(queryParam, results, takeawayPage.getTotal());
	}

	/**
	 * 登录人为 城市骨干 角色
	 */
	public PaginationData<SupplierWorkOrderVO> queryWorkOrderList(PaginationRequest<SupplierWorkOrderQueryParam> queryParam) {
		Page<WorkOrderDO> page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize());
		SupplierWorkOrderQueryParam workOrderQueryParam = queryParam.getQueryParameter();
		if (SupplierWorkOrderConstant.COMPANY_ID_0000.equals(workOrderQueryParam.getCompanyId()) || SupplierWorkOrderConstant.COMPANY_ID_1111.equals(workOrderQueryParam.getCompanyId())) {
			workOrderQueryParam.setCompanyId("");
		}
		//查询全部数据
		if (StringUtils.isNotBlank(workOrderQueryParam.getDocumentStatus()) && SupplierWorkOrderConstant.DOCUMENT_STATUS_ALL.equals(workOrderQueryParam.getDocumentStatus())) {
			workOrderQueryParam.setDocumentStatus("");
		}
		LambdaQueryWrapper<WorkOrderDO> queryWrapper = workOrderBaseService.builderWrapper(workOrderQueryParam);
		Page<WorkOrderDO> workOrderDOS = workOrderMapper.selectPage(page, queryWrapper);
		List<WorkOrderDO> workOrderDOSRecords = workOrderDOS.getRecords();

		if (CollectionUtils.isEmpty(workOrderDOSRecords)) {
			return ResponseUtil.emptyResponse(queryParam, SupplierWorkOrderVO.class, workOrderDOS.getTotal());
		}

		List<SupplierWorkOrderVO> workOrderVOS = workOrderDOSRecords.stream().map(s -> {
			SupplierWorkOrderVO workOrderVO = new SupplierWorkOrderVO();
			BeanUtils.copyProperties(s, workOrderVO);
			if (StringUtils.isNotBlank(s.getReceiver()) && StringUtils.isNotBlank(s.getReceiverMobile())) {
				String receiverAndReceiverMobile = getReceiverAndReceiverMobile(s.getReceiver(), s.getReceiverMobile());
				workOrderVO.setReceiverData(receiverAndReceiverMobile);
			}
			if (Objects.nonNull(s.getDocumentType())) {
				workOrderVO.setDocumentTypeValue(Objects.requireNonNull(OrderStatusEnum.getByType(s.getDocumentType())).getDesc());
			}
			if (Objects.nonNull(s.getDocumentStatus())) {
				workOrderVO.setDocumentStatusValue(Objects.requireNonNull(StoreWorkOrderStatusEnum.getByType(s.getDocumentStatus())).getDesc());
			}
			boolean orderExpiredFlag = false;
			if (Objects.nonNull(s.getExpiredTime())) {
				//工单过期申述有效期 48小时
				orderExpiredFlag = DateUtil.getOrderExpiredDate(s.getExpiredTime(), orderExpire);
			}
			if (StringUtils.isNotBlank(s.getAppealResult()) && OrderAppealStatusEnum.N.getType().equals(s.getAppealResult())) {
				orderExpiredFlag = false;
			}
			workOrderVO.setOrderExpiredFlag(orderExpiredFlag);
			return workOrderVO;
		}).collect(Collectors.toList());

		return ResponseUtil.commonResponse(queryParam, workOrderVOS, workOrderDOS.getTotal());
	}

	public static String getReceiverAndReceiverMobile(String receiverName, String mobile) {
		String[] receiver = receiverName.split(",");
		String[] receiverMobile = mobile.split(",");
		String result = joinStringArrays(receiver, receiverMobile);
		return result;
	}

	public static String joinStringArrays(String[] name,String[] phone){
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < name.length; i++) {
			sb.append(name[i]).append("(")
				.append(phone[i % phone.length])
				.append("),");
		}
		return sb.deleteCharAt(sb.lastIndexOf(",")).toString();
	}


	/**
	 * 扫码接单
	 *
	 * @param scanCodePlaceOrderParam 入参
	 * @return 出参
	 */
	@Transactional(rollbackFor = Exception.class)
	public ScanResponse queryWorkOrder(ScanCodePlaceOrderParam scanCodePlaceOrderParam) {
		ScanResponse scanResponse = new ScanResponse();
		//如果登录人是主账号，直接返回扫码成功，
//		if (Objects.nonNull(scanCodePlaceOrderParam.getUserType())
//			&& SupplierWorkOrderConstant.USER_TYPE_MAIN_ACCOUNT.equals(String.valueOf(scanCodePlaceOrderParam.getUserType()))) {
//			scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_SUCCESS_CODE);
//			scanResponse.setResponseMessage(BizErrorCode.SCAN_SUCCESS.getErrorMsg());
//			return scanResponse;
//		}
		if (Objects.isNull(scanCodePlaceOrderParam) || StringUtils.isBlank(scanCodePlaceOrderParam.getStoreCode())) {
			scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_FAIL_CODE);
			scanResponse.setResponseMessage(BizErrorCode.PARAMETER_OR_STORE_CODE_IS_NULL.getErrorMsg());
			return scanResponse;
		}
		List<WorkOrderDO> workOrderDOList = workOrderBaseService.queryWorkOrder(scanCodePlaceOrderParam);
		if (CollectionUtils.isNotEmpty(workOrderDOList)) {
			for (WorkOrderDO workOrderDO : workOrderDOList) {
				List<WorkOrderReceiverDO> workOrderReceiverDOList = workOrderReceiverBaseService.queryOrderByWorkOrderNumber(workOrderDO.getWorkOrderNumber());
				//如果当前扫码的接单人所属供应商信息和之前接单人所属供应商不一致，直接返回提示：该工单已被其他供应商接单!
//				List<WorkOrderReceiverDO> workOrderReceiverDOList = supplierWorkOrderBaseService.getAllByStoreCode(workOrderDO.getStoreCode());
//				if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
//					//收集供应商id
//					List<Long> supplierIdList = workOrderReceiverDOList.stream()
//						.map(WorkOrderReceiverDO::getSupplierId).distinct().collect(Collectors.toList());
//					if (Objects.nonNull(scanCodePlaceOrderParam.getSupplierId())
//						&& !supplierIdList.contains(scanCodePlaceOrderParam.getSupplierId())) {
//						scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_FAIL_CODE);
//						scanResponse.setResponseMessage(BizErrorCode.SUPPLIER_NO_TAKING_ORDERS.getErrorMsg());
//						return scanResponse;
//					}
//				}
				//然后如果是待接单状态则将状态修改为待执行,添加待交接状态验证
				if (StoreWorkOrderStatusEnum.TO_BE_HANDED_OVER.getType().equals(workOrderDO.getDocumentStatus())
					|| StoreWorkOrderStatusEnum.PENDING_ORDERS.getType().equals(workOrderDO.getDocumentStatus())) {
					if (!StringUtils.equals(scanCodePlaceOrderParam.getSupplierNo(), workOrderDO.getSupplierNo())) {
						scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_FAIL_CODE);
						scanResponse.setResponseMessage(BizErrorCode.NO_NORMAL_SUPPLIER_FAIL.getErrorMsg());
						return scanResponse;
					}
					//设置工单状态为待执行
					workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.TO_BE_EXECUTED.getType());
					//赋值接单人,接单人电话,供应商
					workOrderDO.setReceiver(scanCodePlaceOrderParam.getReceiver());
					workOrderDO.setReceiverMobile(scanCodePlaceOrderParam.getReceiverMobile());
//					workOrderDO.setSupplier(scanCodePlaceOrderParam.getSupplier());
//					workOrderDO.setSupplierNo(scanCodePlaceOrderParam.getSupplierNo());
					saveWorkOrderInfo(scanCodePlaceOrderParam, workOrderDO);
					scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_SUCCESS_CODE);
					scanResponse.setResponseMessage(BizErrorCode.TAKING_ORDERS_SUCCESS.getErrorMsg());
					//应3.30业务修改：扫码成功,接单成功后返回添加工单id，
					scanResponse.setWorkOrderId(workOrderDO.getId());
				} else if (StoreWorkOrderStatusEnum.TO_BE_EXECUTED.getType().equals(workOrderDO.getDocumentStatus())
					|| StoreWorkOrderStatusEnum.IN_PROGRESS.getType().equals(workOrderDO.getDocumentStatus())) {
					if (!StringUtils.equals(scanCodePlaceOrderParam.getSupplierNo(), workOrderDO.getSupplierNo())) {
						scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_FAIL_CODE);
						scanResponse.setResponseMessage(BizErrorCode.NO_NORMAL_SUPPLIER_FAIL.getErrorMsg());
						return scanResponse;
					}
					if (StringUtils.isNotBlank(workOrderDO.getReceiver()) && StringUtils.isNotBlank(workOrderDO.getReceiverMobile())) {
						if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
							//收集接单人id
							List<Long> receiverIdList = workOrderReceiverDOList.stream()
								.map(WorkOrderReceiverDO::getReceiverId).distinct().collect(Collectors.toList());
							if (Objects.nonNull(scanCodePlaceOrderParam.getReceiverID())
								&& !receiverIdList.contains(scanCodePlaceOrderParam.getReceiverID())) {
								workOrderDO.setReceiver(workOrderDO.getReceiver().concat(SupplierWorkOrderConstant.COMMA)
									.concat(scanCodePlaceOrderParam.getReceiver()));
								workOrderDO.setReceiverMobile(workOrderDO.getReceiverMobile().concat(SupplierWorkOrderConstant.COMMA)
									.concat(scanCodePlaceOrderParam.getReceiverMobile()));
								saveWorkOrderInfo(scanCodePlaceOrderParam, workOrderDO);
								scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_SUCCESS_CODE);
								scanResponse.setResponseMessage(BizErrorCode.TAKING_ORDERS_SUCCESS.getErrorMsg());
								//应3.30业务修改：扫码成功,接单成功后返回添加工单id，
								scanResponse.setWorkOrderId(workOrderDO.getId());
							} else {
								scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_SUCCESS_CODE);
								scanResponse.setResponseMessage(BizErrorCode.SCAN_SUCCESS.getErrorMsg());
								//应3.30业务修改：扫码成功,接单成功后返回添加工单id，
								scanResponse.setWorkOrderId(workOrderDO.getId());
							}
						}
					}
				} else {
					scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_SUCCESS_CODE);
					scanResponse.setResponseMessage(BizErrorCode.SCAN_SUCCESS.getErrorMsg());
					//应3.30业务修改：扫码成功,接单成功后返回添加工单id，
					scanResponse.setWorkOrderId(workOrderDO.getId());
				}
			}
		} else {
			scanResponse.setResponseCode(SupplierWorkOrderConstant.SCAN_FAIL_CODE);
			scanResponse.setResponseMessage(BizErrorCode.STORE_NO_WORK_ORDER.getErrorMsg());
		}
		return scanResponse;
	}

	/**
	 * 抽取做成共通方法：更新 工单表数据信息 + 工单-接单人关联关系数据信息
	 *
	 * @param scanCodePlaceOrderParam 扫码下单入参对象
	 * @param workOrderDO             工单表数据信息
	 */
	private void saveWorkOrderInfo(ScanCodePlaceOrderParam scanCodePlaceOrderParam, WorkOrderDO workOrderDO) {
		//优先判断当前扫码人是否已存在该门店的工单中
		List<WorkOrderReceiverDO> workOrderReceiverDOList = supplierWorkOrderBaseService.getByFix(
			scanCodePlaceOrderParam.getReceiverID(), scanCodePlaceOrderParam.getStoreCode(), workOrderDO.getWorkOrderNumber());
		if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
			return;
		}
		//保存工单信息
		//新增接单时间(暂时只取第一个接单人的接单时间)
		if (Objects.isNull(workOrderDO.getOrderReceivingTime())) {
			workOrderDO.setOrderReceivingTime(new Date());
			workOrderDO.setUpdateTime(new Date());
		}
		workOrderBaseService.updateById(workOrderDO);
		//新增工单-接单人关联关系
		WorkOrderReceiverDO workOrderReceiverDO = new WorkOrderReceiverDO();
		workOrderReceiverDO.setReceiverId(scanCodePlaceOrderParam.getReceiverID());
		workOrderReceiverDO.setWorkOrderId(workOrderDO.getId());
		workOrderReceiverDO.setWorkOrderNumber(workOrderDO.getWorkOrderNumber());
		workOrderReceiverDO.setStoreCode(workOrderDO.getStoreCode());
		workOrderReceiverDO.setStoreName(workOrderDO.getStoreName());
		workOrderReceiverDO.setDocumentType(workOrderDO.getDocumentType());
		workOrderReceiverDO.setDocumentStatus(workOrderDO.getDocumentStatus());
		workOrderReceiverDO.setDocumentScore(workOrderDO.getDocumentScore());
		workOrderReceiverDO.setReceiver(scanCodePlaceOrderParam.getReceiver());
		workOrderReceiverDO.setSupplier(scanCodePlaceOrderParam.getSupplier());
		workOrderReceiverDO.setSupplierId(scanCodePlaceOrderParam.getSupplierId());
		workOrderReceiverDO.setSupplierNo(workOrderDO.getSupplierNo());
		workOrderReceiverDO.setCreateTime(new Date());
		workOrderReceiverDO.setUpdateTime(new Date());
		workOrderReceiverDO.setReceiverMobile(scanCodePlaceOrderParam.getReceiverMobile());
		//查询门店信息保存公司信息
		StoreDO storeDO = storeBaseService.queryStoreByStoreNo(workOrderDO.getStoreCode());
		if (Objects.nonNull(storeDO)) {
			workOrderReceiverDO.setCompanyId(storeDO.getCompanyId());
			workOrderReceiverDO.setCompanyName(storeDO.getCompanyName());
		}
		supplierWorkOrderBaseService.insert(workOrderReceiverDO);
	}

	/**
	 * 获取获取 子公司/门店 （主账户查询供应商的子公司/门店，子账户查询自己对应的子公司/门店）
	 *
	 * @param getCompanyStoreParam 获取 子公司/门店 入参
	 * @return list
	 */
	public List<CompanyVO> getCompanyList(GetCompanyStoreParam getCompanyStoreParam) {
		return supplierWorkOrderBaseService.getCompanyList(getCompanyStoreParam);
	}

	/**
	 * 获取获取 子公司-门店 （主账户查询供应商的子公司-门店，子账户查询自己对应的子公司-门店）
	 *
	 * @param queryParam 获取 子公司-门店 入参
	 * @return list
	 */
	public PaginationData<CompanyStorePageVO> getCompanyStoreList(PaginationRequest<GetCompanyStoreParam> queryParam) {
		Page<WorkOrderReceiverDO> page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize());
		Page<CompanyStorePageVO> takeawayPage = supplierWorkOrderBaseService.getCompanyStoreList(queryParam.getQueryParameter(), page);
		if (CollectionUtils.isEmpty(takeawayPage.getRecords())) {
			return ResponseUtil.emptyResponse(queryParam, CompanyStorePageVO.class, takeawayPage.getTotal());
		}
		return ResponseUtil.commonResponse(queryParam, takeawayPage.getRecords(), takeawayPage.getTotal());
	}

	/**
	 * 通过门店编码查询子公司id/name
	 *
	 * @param reQueryCompanyParam 门店编码
	 * @return CompanyStoreVO
	 */
	public CompanyStoreVO reQueryCompanyParam(ReQueryCompanyParam reQueryCompanyParam) {
		if (StringUtils.isBlank(reQueryCompanyParam.getStoreCode())) {
			throw new BizException(BizErrorCode.PARAMETER_IS_NULL);
		}
		StoreDO storeDO = storeBaseService.queryStoreByStoreNo(reQueryCompanyParam.getStoreCode());
		if (Objects.isNull(storeDO)) {
			throw new BizException(BizErrorCode.NOT_GTE_STORE_INFO);
		}
		CompanyStoreVO companyStoreVO = new CompanyStoreVO();
		companyStoreVO.setStoreCode(reQueryCompanyParam.getStoreCode());
		companyStoreVO.setCompanyId(StringUtils.isNotBlank(storeDO.getCompanyId()) ? storeDO.getCompanyId() : "");
		companyStoreVO.setCompanyName(StringUtils.isNotBlank(storeDO.getCompanyName()) ? storeDO.getCompanyName() : "");
		return companyStoreVO;
	}

	/**
	 * 点击工单列表查询 工单信息+任务信息
	 *
	 * @param workOrderId 工单id对象
	 * @return 工单信息+任务信息
	 */
	public SupplierWorkOrderTaskVO queryData(Long workOrderId) {
		SupplierWorkOrderTaskVO supplierWorkOrderTaskVO = new SupplierWorkOrderTaskVO();
		//获取工单信息
		WorkOrderDO workOrderDO = workOrderBaseService.selectById(workOrderId);
		if (Objects.nonNull(workOrderDO)) {
			BeanUtils.copyProperties(workOrderDO, supplierWorkOrderTaskVO);
			//接单人信息赋值
			if (StringUtils.isNotBlank(workOrderDO.getReceiver()) && StringUtils.isNotBlank(workOrderDO.getReceiverMobile())) {
				List<WorkOrderReceiverDO> workOrderReceiverDOList = supplierWorkOrderBaseService.getAllByWorkOrderNumber(workOrderDO.getWorkOrderNumber());
				if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
					String receiverData = getReceiverData(workOrderReceiverDOList);
					supplierWorkOrderTaskVO.setReceiverData(receiverData);
				}
			}
			supplierWorkOrderTaskVO.setDocumentTypeValue(Objects.requireNonNull(OrderStatusEnum.getByType(supplierWorkOrderTaskVO.getDocumentType())).getDesc());
			supplierWorkOrderTaskVO.setDocumentStatusValue(Objects.requireNonNull(StoreWorkOrderStatusEnum.getByType(supplierWorkOrderTaskVO.getDocumentStatus())).getDesc());
			//查询工单关联的任务信息
			List<TaskExecutionDO> taskExecutionDOList = taskExecutionBaseService.selectByWorkOrderNumber(workOrderDO.getWorkOrderNumber());
			if (CollectionUtils.isNotEmpty(taskExecutionDOList)) {
				String yesterday = DateUtil.getYearsDate(workOrderDO.getCreateTime());
				List<TaskExecutionDetailVO> taskExecutionDetailVOList = new ArrayList<>();

				GetTaskRequest getTaskRequest = new GetTaskRequest();
				getTaskRequest.setYesterday(yesterday);
				getTaskRequest.setStoreCode(workOrderDO.getStoreCode());
				List<TaskExecutionDO> yesterdayTask = taskExecutionBaseService.getTaskExecutionEarlyAcceptance(getTaskRequest);
				Map<String, List<TaskExecutionDO>> taskMap  = yesterdayTask.stream().collect(Collectors.groupingBy(TaskExecutionDO::getTaskId));

				//获取工单的验收完成时间,并对其时间进行验证（是否已超出当前时间）
				boolean flag = false;
				if (Objects.nonNull(workOrderDO.getAcceptanceCompletionTime())) {
					//已验收过，
					flag = verificationTime(workOrderDO.getAcceptanceCompletionTime());
				}
				//未验收过，
				boolean finalFlag = flag;
				taskExecutionDOList.forEach(taskExecutionDO -> {
					TaskExecutionDetailVO taskExecutionDetailVO = new TaskExecutionDetailVO();
					BeanUtils.copyProperties(taskExecutionDO, taskExecutionDetailVO);
					//处理图片string->list
					//示意图
					String schematicDrawing = taskExecutionDO.getSchematicDrawing();
					if (StringUtils.isNotBlank(schematicDrawing)) {
						taskExecutionDetailVO.setSchematicDrawing(JSONArray.parseArray(schematicDrawing, FileVO.class));
					}
					//处理任务的拍照图片
					String takePictures = taskExecutionDO.getTakePictures();
					if (StringUtils.isNotBlank(takePictures)) {
						taskExecutionDetailVO.setTakePictures(JSONArray.parseArray(takePictures, AiResultVO.class));
					}
					taskExecutionDetailVO.setTaskExecutionId(taskExecutionDO.getId());
					if (Objects.nonNull(taskExecutionDetailVO.getClosingInspection())) {
						taskExecutionDetailVO.setClosingInspectionValue(Objects.requireNonNull(ClosingInspectionEnum.queryByType(taskExecutionDetailVO.getClosingInspection())).getDesc());
					}
					if (Objects.nonNull(taskExecutionDetailVO.getNoSuchItemFlag())) {
						taskExecutionDetailVO.setNoSuchItemFlagValue(Objects.requireNonNull(NoSuchItemEnum.queryByType(taskExecutionDetailVO.getNoSuchItemFlag())).getDesc());
					}
					if (Objects.nonNull(taskExecutionDetailVO.getDealStatus())) {
						taskExecutionDetailVO.setDealStatusValue(Objects.requireNonNull(TaskDealStatusEnum.queryByType(taskExecutionDetailVO.getDealStatus())).getDesc());
					}
					//获取该任务昨日的验收结果（满意/不满意/无此项）
//					getTaskRequest.setTaskId(taskExecutionDO.getTaskId());
//					String taskExecutionEarlyAcceptance = taskExecutionBaseService.getTaskExecutionEarlyAcceptance(getTaskRequest);
//					if (StringUtils.isNotBlank(taskExecutionEarlyAcceptance)) {
//						taskExecutionDetailVO.setYesterdayEarlyAcceptance(taskExecutionEarlyAcceptance);
//					}

					List<TaskExecutionDO> taskExecutionDOS = taskMap.get(taskExecutionDO.getTaskId());
					if (CollectionUtil.isNotEmpty(taskExecutionDOS)) {
						boolean anyMatch = taskExecutionDOS.stream().anyMatch(s -> StringUtils.equals(StoreTaskEnum.NO.getType(), s.getEarlyAcceptance()));
						if (anyMatch) {
							taskExecutionDetailVO.setYesterdayEarlyAcceptance(StoreTaskEnum.NO.getType());
						}
					}

					//工单的<1任务验收状态只有不满意>和<2申诉状态为null或者已驳回>以及<3满足固定时效内>时，显示‘去申诉’按钮，展示标识符flag（true展示；false不展示）
					if (StoreTaskEnum.TASK_APPEAL_TYPE.contains(taskExecutionDO.getEarlyAcceptance())
						&& taskExecutionDO.getAppealStatus() == null
						&& finalFlag) {
						taskExecutionDetailVO.setShowAppealFlag(true);
					}
					//任务的申诉状态
					if (Objects.nonNull(taskExecutionDetailVO.getAppealStatus())) {
						taskExecutionDetailVO.setAppealStatusValue(Objects.requireNonNull(AppealStatusEnum.getByType(taskExecutionDetailVO.getAppealStatus())).getDesc());
					}

					if (StringUtils.equals(taskExecutionDO.getEarlyAcceptance(),StoreTaskEnum.NO.getType())) {
						taskExecutionDetailVO.setSortNum(NumberUtils.INTEGER_ONE);
					} else {
						taskExecutionDetailVO.setSortNum(NumberUtils.INTEGER_ZERO);
					}
					taskExecutionDetailVOList.add(taskExecutionDetailVO);
				});
				List<TaskExecutionDetailVO> taskExecutionList = taskExecutionDetailVOList.stream().sorted(Comparator.comparing(TaskExecutionDetailVO::getSortNum, Comparator.reverseOrder())).collect(Collectors.toList());
				supplierWorkOrderTaskVO.setTaskExecutionDetailVOList(taskExecutionList);
			}
			//获取工单关联的设备信息
			//先获取apollo里的设备信息
			List<WorkOrderDeviceDetailVO> workOrderDeviceDetailVOList = new ArrayList<>();
			Map<String, String> map = JSONObject.parseObject(storeOrderDeviceConfig.getOrderDevice(), Map.class);
			if (!map.isEmpty()) {
				map.forEach((name, sign) -> {
					WorkOrderDeviceDetailVO workOrderDeviceDetailVO = new WorkOrderDeviceDetailVO();
					workOrderDeviceDetailVO.setWorkOrderNumber(workOrderDO.getWorkOrderNumber());
					workOrderDeviceDetailVO.setStoreCode(workOrderDO.getStoreCode());
					workOrderDeviceDetailVO.setDeviceName(name);
					workOrderDeviceDetailVO.setDeviceSign(sign);
					workOrderDeviceDetailVO.setDeviceNumber("-");
					workOrderDeviceDetailVO.setOperation(1);
					workOrderDeviceDetailVOList.add(workOrderDeviceDetailVO);
				});
			}
			if (CollectionUtils.isNotEmpty(workOrderDeviceDetailVOList)) {
				//获取工单关联的设备信息
				List<StoreOrderDeviceDO> storeOrderDeviceDOList = workOrderDeviceBaseService.getDeviceList(workOrderDO.getWorkOrderNumber());
				if (CollectionUtils.isNotEmpty(storeOrderDeviceDOList)) {
					workOrderDeviceDetailVOList.forEach(workOrderDeviceDetailVO -> {
						storeOrderDeviceDOList.stream()
							.filter(storeOrderDeviceDO -> storeOrderDeviceDO.getDeviceName().equals(workOrderDeviceDetailVO.getDeviceName()))
							.findFirst()
							.ifPresent(storeOrderDeviceDO -> {
								workOrderDeviceDetailVO.setDeviceNumber(String.valueOf(storeOrderDeviceDO.getDeviceNumber()));
								workOrderDeviceDetailVO.setOperation(storeOrderDeviceDO.getOperation());
								workOrderDeviceDetailVO.setRemark(storeOrderDeviceDO.getRemark());
							});
					});
				}
				supplierWorkOrderTaskVO.setWorkOrderDeviceDetailVOList(workOrderDeviceDetailVOList);
			}
			//获取工单的供应商需要确认的信息
			if (StringUtils.isNotBlank(workOrderDO.getDeviceTakeOver())) {
				String deviceTakeOver = workOrderDO.getDeviceTakeOver();
				supplierWorkOrderTaskVO.setDeviceTakeOverList(JSONArray.parseArray(deviceTakeOver, DescVO.class));
			}
			boolean orderExpiredFlag = false;
			if (Objects.nonNull(workOrderDO.getExpiredTime())) {
				//工单过期申述有效期 48小时
				orderExpiredFlag = DateUtil.getOrderExpiredDate(workOrderDO.getExpiredTime(), orderExpire);
			}
			if (StringUtils.isNotBlank(workOrderDO.getAppealResult()) && OrderAppealStatusEnum.N.getType().equals(workOrderDO.getAppealResult())) {
				orderExpiredFlag = false;
			}
			supplierWorkOrderTaskVO.setOrderExpiredFlag(orderExpiredFlag);

		}
		return supplierWorkOrderTaskVO;
	}

	private static String getReceiverData(List<WorkOrderReceiverDO> workOrderReceiverDOList) {
		String receiverData = "";
		for (int i = 0; i < workOrderReceiverDOList.size(); i++) {
			WorkOrderReceiverDO workOrderReceiverDO = workOrderReceiverDOList.get(i);
			if (i == workOrderReceiverDOList.size() - 1) {
				receiverData = receiverData + workOrderReceiverDO.getReceiver().concat("(").concat(workOrderReceiverDO.getReceiverMobile()).concat(")");
			} else {
				receiverData = receiverData + workOrderReceiverDO.getReceiver().concat("(").concat(workOrderReceiverDO.getReceiverMobile()).concat(")").concat(",");
			}
		}
		return receiverData;
	}

	private Boolean verificationTime(Date acceptanceCompletionTime) {
		// 计算currentTime和acceptanceCompletionTime之间的时间差
		Date currentTime = new Date();
		long diffInMillies = Math.abs(currentTime.getTime() - acceptanceCompletionTime.getTime());
		long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillies);
		// 判断时间差是否在0到24小时之间(24是可配置项)
		return diffInHours >= 0 && diffInHours <= hours;
	}

	/**
	 * 根据工单编号查询工单信息
	 *
	 * @param supplierDealWorkOrderParam 工单编号
	 * @return 工单信息
	 */
	@Transactional(rollbackFor = Exception.class)
	public SupplierWorkOrderTaskVO dealWorkOrder(SupplierDealWorkOrderParam supplierDealWorkOrderParam) {
		SupplierWorkOrderTaskVO supplierWorkOrderTaskVO = new SupplierWorkOrderTaskVO();
		//先判断所有的任务是否已全部完成，完成的才可以完成打烊任务，否则提示：请先处理工单关联的任务信息!
		List<TaskExecutionDO> taskExecutionDOList = taskExecutionBaseService.dealWorkOrder(supplierDealWorkOrderParam);
		if (CollectionUtils.isNotEmpty(taskExecutionDOList)) {
			taskExecutionDOList.forEach(taskExecutionDO -> {
				if (TaskDealStatusEnum.NO.getType().equals(taskExecutionDO.getDealStatus())) {
					throw new BizException(BizErrorCode.WORK_ORDER_HAS_WORK_AND_NO_DEAL.getErrorMsg());
				}
			});
		}
		//获取工单信息
		WorkOrderDO workOrderDO = workOrderBaseService.dealWorkOrder(supplierDealWorkOrderParam.getWorkOrderNumber());
		if (Objects.nonNull(workOrderDO)) {
			//将工单状态改为 待验收
			workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.TO_BE_ACCEPTED.getType());
			//新增打烊完成时间
			workOrderDO.setClosingTime(new Date());
			workOrderDO.setUpdateTime(new Date());
			workOrderBaseService.update(workOrderDO);
			//同时修改工单-接单人关联表状态信息
			List<WorkOrderReceiverDO> workOrderReceiverDOList = supplierWorkOrderBaseService.selectListByWorkOrderId(workOrderDO.getId());
			if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
				List<WorkOrderReceiverDO> updateList = new ArrayList<>();
				workOrderReceiverDOList.forEach(workOrderReceiverDO -> {
					workOrderReceiverDO.setDocumentStatus(StoreWorkOrderStatusEnum.TO_BE_ACCEPTED.getType());
					workOrderReceiverDO.setUpdateTime(new Date());
					updateList.add(workOrderReceiverDO);
				});
				supplierWorkOrderBaseService.updateBatchById(updateList);
			}
			BeanUtils.copyProperties(workOrderDO, supplierWorkOrderTaskVO);
			supplierWorkOrderTaskVO.setDocumentTypeValue(Objects.requireNonNull(OrderStatusEnum.getByType(supplierWorkOrderTaskVO.getDocumentType())).getDesc());
			supplierWorkOrderTaskVO.setDocumentStatusValue(Objects.requireNonNull(StoreWorkOrderStatusEnum.getByType(supplierWorkOrderTaskVO.getDocumentStatus())).getDesc());

			List<String> stringList = Arrays.asList(taskName.split(SupplierWorkOrderConstant.COMMA));
			for (TaskExecutionDO taskExecutionDO : taskExecutionDOList) {
				// 当图片AI结果为不合格时需发送消息通知
				if (stringList.contains(taskExecutionDO.getTaskName()) && SupplierWorkOrderConstant.AI_RESULT_NO.equals(taskExecutionDO.getAiResult())) {

					StoreIssueNoticeParam storeIssueNoticeParam = new StoreIssueNoticeParam();
					storeIssueNoticeParam.setStoreNo(workOrderDO.getStoreCode());
					storeIssueNoticeParam.setId(String.valueOf(taskExecutionDO.getId()));
					storeIssueNoticeParam.setIssueType(ForewarningTypeEnum.ORDER_ACCEPTANCE_FOREWARNING.getType());
					storeIssueNoticeParam.setIssueDescription(aiResultDesc);
					List<AiResultVO> takePictures = JSON.parseArray(taskExecutionDO.getTakePictures(), AiResultVO.class);
					List<TaskPicPushVO> picPushVOS = takePictures.stream().filter(t -> StringUtils.isNotBlank(t.getType())).map(s -> {
						TaskPicPushVO taskPicPushVO = new TaskPicPushVO();
						BeanUtils.copyProperties(s, taskPicPushVO);
						if (StringUtils.isNotEmpty(s.getType())) {
							taskPicPushVO.setLocationName(IdentifyImageLocationEnum.getByType(s.getType()).getDesc());
						}
						return taskPicPushVO;
					}).collect(Collectors.toList());
					List<AiResultVO> pictureInfoVOS = getAiException(takePictures);
					Map<String, Object> hashMap = new HashMap<>();
					hashMap.put("allPicList", picPushVOS);
					hashMap.put("pictureInfoList", pictureInfoVOS);
					storeIssueNoticeParam.setExtData(JSONObject.toJSONString(hashMap));
					log.info("完成工单发送消息通知iot:{} {} {}", workOrderDO.getWorkOrderNumber(), taskExecutionDO.getId(), JSONObject.toJSONString(storeIssueNoticeParam));
					storeAppSweepService.sendMessage(storeIssueNoticeParam);

				}
			}
		}
		return supplierWorkOrderTaskVO;
	}

	//智能茶饮机
	public List<AiResultVO> getAiException(List<AiResultVO> takePictures) {
		List<AiResultVO> pictureInfoVOS = new ArrayList<>();

		//出茶口请求成功但是不合格code，
		List<String> teaOutletAiSuccessCodeList = SupplierWorkOrderConstant.TEA_OUTLET_AI_SUCCESS_CODE;
		//料仓请求成功但是不合格code，
		List<String> siloAiSuccessCodeList = SupplierWorkOrderConstant.SILO_AI_SUCCESS_CODE;
		//出风口请求成功但是不合格code，
		List<String> outletAiSuccessCodeList = SupplierWorkOrderConstant.OUTLET_AI_SUCCESS_CODE;
		//蠕动泵请求成功但是不合格code，
		List<String> peristalticPumpAiSuccessCodeList = SupplierWorkOrderConstant.PERISTALTIC_PUMP_AI_SUCCESS_CODE;

		for (AiResultVO fileVO : takePictures) {
			if (StringUtils.isNotBlank(fileVO.getType())) {
				IdentifyImageLocationEnum byType = IdentifyImageLocationEnum.getByType(fileVO.getType());
				if (Objects.isNull(byType)) {
					log.info("未匹配该识别位置，IdentifyImageLocationEnum：{}", fileVO.getType());
					continue;
				}
				switch (byType){
					case TEA_OUTLET:
						if (CollectionUtils.isNotEmpty(teaOutletAiSuccessCodeList) && teaOutletAiSuccessCodeList.contains(fileVO.getCode().toString())) {
							pictureInfoVOS.add(fileVO);
						}
						break;
					case SILO:
						if (CollectionUtils.isNotEmpty(siloAiSuccessCodeList) && siloAiSuccessCodeList.contains(fileVO.getCode().toString())) {
							pictureInfoVOS.add(fileVO);
						}
						break;
					case OUTLET:
						if (CollectionUtils.isNotEmpty(outletAiSuccessCodeList) && outletAiSuccessCodeList.contains(fileVO.getCode().toString())) {
							pictureInfoVOS.add(fileVO);
						}
						break;
					case PERISTALTIC_PUMP:
						if (CollectionUtils.isNotEmpty(peristalticPumpAiSuccessCodeList) && peristalticPumpAiSuccessCodeList.contains(fileVO.getCode().toString())) {
							pictureInfoVOS.add(fileVO);
						}
						break;
				}
			}
		}

		return pictureInfoVOS;
	}


	/**
	 * 供应商确认预打烊交接信息
	 *
	 * @param supplierDeviceConfirmHandoverParam 工单编号+确认预打烊交接信息
	 * @return 工单信息
	 */
	@Transactional(rollbackFor = Exception.class)
	public Boolean confirmHandoverData(SupplierDeviceConfirmHandoverParam supplierDeviceConfirmHandoverParam) {
		boolean b = false;
		if (Objects.isNull(supplierDeviceConfirmHandoverParam) || StringUtils.isBlank(supplierDeviceConfirmHandoverParam.getWorkOrderNumber())) {
			throw new BizException(BizErrorCode.PARAMETER_OR_WORK_ORDER_NUM_IS_NULL.getErrorMsg());
		}
		//验证供应商确认的预打烊完成情况交接信息是否有值
		List<SupplierConfirmationParam> confirmHandoverList = supplierDeviceConfirmHandoverParam.getConfirmHandoverList();
		if (CollectionUtils.isEmpty(confirmHandoverList)) {
			throw new BizException(BizErrorCode.NO_HANDOVER.getErrorMsg());
		}
		confirmHandoverList.forEach(supplierConfirmationRequest -> {
			if (StringUtils.isBlank(supplierConfirmationRequest.getConfirmStatus())) {
				throw new BizException(supplierConfirmationRequest.getDesc() + BizErrorCode.NO_HANDOVER_CONFIRM_STATUS.getErrorMsg());
			}
		});
		//获取工单信息
		LambdaQueryWrapper<WorkOrderDO> workOrderDoQueryWrapper = new LambdaQueryWrapper<>();
		workOrderDoQueryWrapper
			.eq(StringUtils.isNotBlank(supplierDeviceConfirmHandoverParam.getWorkOrderNumber()), WorkOrderDO::getWorkOrderNumber,
				supplierDeviceConfirmHandoverParam.getWorkOrderNumber())
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		WorkOrderDO workOrderDO = workOrderBaseService.getOne(workOrderDoQueryWrapper);
		if (Objects.nonNull(workOrderDO)) {
			workOrderDO.setDeviceTakeOver(JSON.toJSONString(confirmHandoverList));
			workOrderDO.setUpdateTime(new Date());
			b = workOrderBaseService.updateById(workOrderDO);
		}
		return b;
	}

	/**
	 * 供应商对工单任务验收结果不合格的提起申诉
	 *
	 * @param submitAppealRequest 提交申诉参数
	 * @return boolean
	 */
	@Transactional(rollbackFor = Exception.class)
	public Boolean submitAppeal(SubmitAppealRequest submitAppealRequest) {
		BladeUser user = AuthUtil.getUser();
		Long userId = user.getUserId();
		String userName = user.getNickName();
		if (Objects.isNull(submitAppealRequest)) {
			throw new BizException(BizErrorCode.PARAMETER_IS_NULL);
		}
		if (StringUtils.isBlank(submitAppealRequest.getWorkOrderNumber()) || Objects.isNull(submitAppealRequest.getStoreTaskRelationId())
			|| StringUtils.isBlank(submitAppealRequest.getTaskName())) {
			throw new BizException(BizErrorCode.WORK_ORDER_NUM_OR_STORE_TASK_RELATION_ID_OR_TASK_NAME_IS_NULL);
		}
		LambdaQueryWrapper<TaskExecutionDO> taskExecutionDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
		taskExecutionDOLambdaQueryWrapper
			.eq(TaskExecutionDO::getWorkOrderNumber, submitAppealRequest.getWorkOrderNumber())
			.eq(TaskExecutionDO::getStoreTaskRelationId, submitAppealRequest.getStoreTaskRelationId())
			.eq(TaskExecutionDO::getTaskName, submitAppealRequest.getTaskName())
			.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		TaskExecutionDO taskExecutionDO = taskExecutionBaseService.getOne(taskExecutionDOLambdaQueryWrapper);
		if (Objects.isNull(taskExecutionDO)) {
			throw new BizException(BizErrorCode.NO_TASK_EXECUTION_DATA);
		}

		if (ObjectUtils.isNotEmpty(taskExecutionDO.getAppealStatus()) && taskExecutionDO.getAppealStatus().equals(AppealStatusEnum.REJECTED.getType())) {
			throw new BizException(BizErrorCode.APPEAL_REJECTED_FAIL);
		}
		//申诉状态
		taskExecutionDO.setAppealStatus(AppealStatusEnum.PENDING_PROCESSING.getType());
		//拓展字段：申诉原因+申诉证明
		AppealExtraVO appealExtraVO = new AppealExtraVO();
		if (StringUtils.isNotBlank(submitAppealRequest.getAppealReason())) {
			appealExtraVO.setAppealReason(submitAppealRequest.getAppealReason());
		}
		if (CollectionUtils.isNotEmpty(submitAppealRequest.getAppealCertificate())) {
			appealExtraVO.setAppealCertificate(submitAppealRequest.getAppealCertificate());
		}
		taskExecutionDO.setExtra(JSONObject.toJSONString(appealExtraVO));
		//更新时间
		taskExecutionDO.setUpdateTime(new Date());
		boolean b = taskExecutionBaseService.updateById(taskExecutionDO);
		if (b) {
			//工单信息
			LambdaQueryWrapper<WorkOrderDO> workOrderDOLambdaQueryWrapper = new LambdaQueryWrapper<>();
			workOrderDOLambdaQueryWrapper
				.eq(WorkOrderDO::getWorkOrderNumber, submitAppealRequest.getWorkOrderNumber())
				.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
			WorkOrderDO workOrderDO = workOrderBaseService.getOne(workOrderDOLambdaQueryWrapper);

			Integer alterBeforeStatus = workOrderDO.getDocumentStatus();
			//此时存在申诉的任务，则需要将工单状态由已完成改成申诉中
			updateWorkOrder(workOrderDO);

			//发送飞书通知
			b = sendFeiShuMessage(submitAppealRequest);

			try {
				TimerEventRegisterDefaultRequest request = new TimerEventRegisterDefaultRequest();
				request.setEventType(EventTypeEnum.CLOSING_TASK_APPEAL);
				request.setBizCode(workOrderDO.getWorkOrderNumber());

				EndOrderAndTaskAppealEventBizDataBO bizDataBO = new EndOrderAndTaskAppealEventBizDataBO().setDocumentStatus(alterBeforeStatus);
				JSONObject bizDate = (JSONObject) JSONObject.toJSON(bizDataBO);
				request.setBizData(bizDate);

				Long expiredDate = System.currentTimeMillis() + (expiredTime * 1000L);
				LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(expiredDate), ZoneId.systemDefault());
				request.setTimer(dateTime);
				log.info("任务申诉注册{}", JSONObject.toJSONString(request));
				SoaResponse<Void, Void> response = iEventApi.registerDefaultTimerEvent(request);
				SoaUtil.unpack(response);
			} catch (Exception e) {
				log.error("任务申诉注册失败", e);
				//throw new BizException(BizErrorCode.PLEASE_WAIT);
			}
			// 操作日志
			OperateRecordRequest operateRecordRequest = new OperateRecordRequest();
			operateRecordRequest.setStoreNo(submitAppealRequest.getWorkOrderNumber());

			OrderAppealRecordBO updateBefore = new OrderAppealRecordBO();
			updateBefore.setDocumentStatus(StoreWorkOrderStatusEnum.getByType(alterBeforeStatus).getDesc());
			operateRecordRequest.setUpdateBefore(JSON.toJSONString(updateBefore));

			OrderAppealRecordBO updateData = new OrderAppealRecordBO();
			updateData.setRecordName(RecordTypeEnum.TASK_APPEAL.getDesc());
			updateData.setDocumentStatus(StoreWorkOrderStatusEnum.IN_APPEAL.getDesc());
			updateData.setStoreTaskRelationId(submitAppealRequest.getStoreTaskRelationId());
			updateData.setTaskName(submitAppealRequest.getTaskName());
			updateData.setAppealReason(submitAppealRequest.getAppealReason());
			updateData.setAppealCertificate(submitAppealRequest.getAppealCertificate());
			operateRecordRequest.setUpdateData(JSON.toJSONString(updateData));

			operateRecordRequest.setUpdateFrom(StrUtil.isNotBlank(userName) ? userName : CommonConstant.OPERATE_SOURCE);
			operateRecordRequest.setUpdateFromCode(String.valueOf(userId));
			operateRecordBizService.updateOptRecord(operateRecordRequest);
		}
		return b;
	}

	/**
	 * 当任务有申诉提交时触发，修改工单状态由已完成改成待处理申诉
	 */
	private void updateWorkOrder(WorkOrderDO workOrderDO) {
		if (Objects.nonNull(workOrderDO)) {
			workOrderDO.setUpdateTime(new Date());
			workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.IN_APPEAL.getType());
			workOrderDO.setAppealFlag(OrderAppealTypeEnum.APPEAL.name());
			workOrderBaseService.update(workOrderDO);
		}
		//2工单接单人信息
		List<WorkOrderReceiverDO> workOrderReceiverDOList = supplierWorkOrderBaseService.getAllByWorkOrderNumber(workOrderDO.getWorkOrderNumber());
		if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
			workOrderReceiverDOList.forEach(workOrderReceiverDO -> {
				workOrderReceiverDO.setUpdateTime(new Date());
				workOrderReceiverDO.setDocumentStatus(StoreWorkOrderStatusEnum.IN_APPEAL.getType());
				supplierWorkOrderBaseService.updateById(workOrderReceiverDO);
			});
		}
	}

	/**
	 * 发送飞书通知
	 *
	 * @param submitAppealRequest submitAppealRequest
	 * @return true/false
	 */
	private boolean sendFeiShuMessage(SubmitAppealRequest submitAppealRequest) {
		log.error("供应商对工单{}的任务{}的验收结果不合格的申诉，发起成功。", submitAppealRequest.getWorkOrderNumber(), submitAppealRequest.getTaskName());
		LambdaQueryWrapper<WorkOrderDO> workOrderDOWrapper = new LambdaQueryWrapper<>();
		workOrderDOWrapper
			.eq(WorkOrderDO::getWorkOrderNumber, submitAppealRequest.getWorkOrderNumber())
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		WorkOrderDO workOrderDO = workOrderMapper.selectOne(workOrderDOWrapper);
		if (Objects.isNull(workOrderDO)) {
			throw new BizException(BizErrorCode.NO_WORK_ORDER_DATA);
		}
		//发送飞书通知
		LarkMessageInfo info = new LarkMessageInfo();
		info.setStoreNo(workOrderDO.getStoreCode());
		info.setWorkOrderNumber(submitAppealRequest.getWorkOrderNumber());
		info.setType(LarkMessageTypeEnum.appealNotice.getType());
		try {
			return feiShuMessageBizService.sendMessage(info);
		} catch (Exception e) {
			log.error("打烊工单{}发送飞书通知失败:", submitAppealRequest.getWorkOrderNumber(), e);
		}
		return false;
	}

	public Boolean orderAppeal(OrderAppealRequest orderAppealRequest) {
		BladeUser user = AuthUtil.getUser();
		String userName = StringUtils.EMPTY;
		if (Objects.nonNull(user)) {
			userName = user.getNickName();
		}
		LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(WorkOrderDO::getWorkOrderNumber, orderAppealRequest.getWorkOrderNumber())
			.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		WorkOrderDO workOrderDO = workOrderBaseService.list(queryWrapper).stream().findFirst().orElse(null);
		if (ObjectUtil.isEmpty(workOrderDO)) {
			throw new BizException(BizErrorCode.ORDER_NOT_EXIST);
		}
		if (!StoreWorkOrderStatusEnum.ORDER_APPEAL_TYPE.contains(workOrderDO.getDocumentStatus())) {
			throw new BizException(BizErrorCode.ORDER_STATUS_FAIL);
		}
		if (StringUtils.equals(workOrderDO.getAppealResult(), OrderAppealStatusEnum.N.getType())) {
			throw new BizException(BizErrorCode.APPEAL_REJECTED_FAIL);
		}

		//工单过期申述有效期 48小时
		if (Objects.nonNull(workOrderDO.getExpiredTime())) {
			Boolean orderExpiredFlag = DateUtil.getOrderExpiredDate(workOrderDO.getExpiredTime(), orderExpire);
			if (orderExpiredFlag && StringUtils.equals(workOrderDO.getAppealResult(), OrderAppealStatusEnum.N.getType())) {
				throw new BizException(BizErrorCode.APPEAL_REJECTED_FAIL);
			}
			if (!orderExpiredFlag) {
				throw new BizException(BizErrorCode.APPEAL_OVERTIME_FAIL);
			}
		}

		Integer alterBefore = workOrderDO.getDocumentStatus();

		OrderExtJsonBO extJsonBO = new OrderExtJsonBO();
		if (StringUtils.isNotBlank(workOrderDO.getExtra())) {
			extJsonBO = JSON.parseObject(workOrderDO.getExtra(), new TypeReference<OrderExtJsonBO>() {
			});
		}
		extJsonBO.setAppealReason(orderAppealRequest.getAppealReason());
		extJsonBO.setAppealPic(orderAppealRequest.getAppealPic());
		workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.EXPIRED_APPEAL.getType());//申诉中
		workOrderDO.setExtra(JSONObject.toJSON(extJsonBO).toString());
		workOrderDO.setAppealTime(new Date());
		workOrderDO.setAppealFlag(OrderAppealTypeEnum.APPEAL.name());
		workOrderBaseService.updateOrderInfo(workOrderDO);

		LambdaQueryWrapper<WorkOrderReceiverDO> receiverWrapper = new LambdaQueryWrapper<>();
		receiverWrapper.eq(WorkOrderReceiverDO::getWorkOrderNumber, orderAppealRequest.getWorkOrderNumber())
			.eq(WorkOrderReceiverDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
		List<WorkOrderReceiverDO> list = workOrderReceiverBaseService.list(receiverWrapper);
		if (CollectionUtils.isNotEmpty(list)) {
			workOrderReceiverBaseService.batchUpdateOrderStatus(list, StoreWorkOrderStatusEnum.EXPIRED_APPEAL.getType(), StringUtils.EMPTY);
		}

		//发送飞书通知
		feiShuSendService.orderAppealFeiShuMsg(workOrderDO);

		try {
			TimerEventRegisterDefaultRequest request = new TimerEventRegisterDefaultRequest();
			request.setEventType(EventTypeEnum.CLOSING_ORDER_APPEAL);
			request.setBizCode(workOrderDO.getWorkOrderNumber());

			EndOrderAndTaskAppealEventBizDataBO bizDataBO = new EndOrderAndTaskAppealEventBizDataBO().setDocumentStatus(alterBefore);
			JSONObject bizDate = (JSONObject) JSONObject.toJSON(bizDataBO);
			request.setBizData(bizDate);

			Long expiredDate = System.currentTimeMillis() + (expiredTime * 1000L);
			LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(expiredDate), ZoneId.systemDefault());
			request.setTimer(dateTime);
			log.info("工单申诉注册{}", JSONObject.toJSONString(request));
			SoaResponse<Void, Void> response = iEventApi.registerDefaultTimerEvent(request);
			SoaUtil.unpack(response);
		} catch (Exception e) {
			log.error("工单申诉注册失败", e);
			//throw new BizException(BizErrorCode.PLEASE_WAIT);
		}

		// 操作日志
		OperateRecordRequest operateRecordRequest = new OperateRecordRequest();
		operateRecordRequest.setStoreNo(orderAppealRequest.getWorkOrderNumber());

		OrderAppealRecordBO updateBefore = new OrderAppealRecordBO();
		updateBefore.setDocumentStatus(StoreWorkOrderStatusEnum.getByType(alterBefore).getDesc());
		operateRecordRequest.setUpdateBefore(JSON.toJSONString(updateBefore));

		OrderAppealRecordBO updateData = new OrderAppealRecordBO();
		updateData.setRecordName(RecordTypeEnum.ORDER_APPEAL.getDesc());
		updateData.setDocumentStatus(StoreWorkOrderStatusEnum.EXPIRED_APPEAL.getDesc());
		updateData.setAppealReason(orderAppealRequest.getAppealReason());
		updateData.setAppealCertificate(orderAppealRequest.getAppealPic());
		operateRecordRequest.setUpdateData(JSON.toJSONString(updateData));

		operateRecordRequest.setUpdateFrom(StrUtil.isNotBlank(userName) ? userName : CommonConstant.SUPPLIER);
		if (Objects.nonNull(user) && Objects.nonNull(user.getUserId())) {
			operateRecordRequest.setUpdateFromCode(String.valueOf(user.getUserId()));
		}
		operateRecordBizService.updateOptRecord(operateRecordRequest);
		return true;
	}



	/**
	 * 供应商对工单的单独任务进行处理/修改
	 *
	 * @param supplierDealTaskRequest 任务处理/修改入参对象
	 * @return TaskExecutionDetailResponse
	 */
	@Transactional(rollbackFor = Exception.class)
	public TaskExecutionDetailResponse dealTask(SupplierDealTaskRequest supplierDealTaskRequest) {
		TaskExecutionDetailResponse taskExecutionDetailResponse = new TaskExecutionDetailResponse();
		//根据工单关联任务表的主键id查询出任务信息
		TaskExecutionDO taskExecutionDO = taskExecutionBaseService.getBaseMapper().selectById(supplierDealTaskRequest.getTaskExecutionId());
		if (Objects.nonNull(taskExecutionDO)) {
			//判断是否是 无此项 任务
			//未选择 无此项
			if (NoSuchItemEnum.NO.getType().equals(supplierDealTaskRequest.getNoSuchItemFlag())) {
				taskExecutionDO.setNoSuchItemFlag(NoSuchItemEnum.NO.getType());
				//供应商清洁员处理任务时的拍照
				List<AiResultVO> takePictures = supplierDealTaskRequest.getTakePictures();

				taskExecutionDO.setTakePictures(CollectionUtils.isNotEmpty(takePictures) ? JSON.toJSONString(takePictures) : "");
					//给 打烊验收 字段赋值 已完成

				taskExecutionDO.setClosingInspection(ClosingInspectionEnum.NO.getType());
			}
			//选择 无此项
			if (NoSuchItemEnum.YES.getType().equals(supplierDealTaskRequest.getNoSuchItemFlag())) {
				taskExecutionDO.setNoSuchItemFlag(NoSuchItemEnum.YES.getType());
				//给 打烊验收 字段赋值 无此项
				taskExecutionDO.setClosingInspection(ClosingInspectionEnum.YES.getType());
				//将上传的图片置空
				taskExecutionDO.setTakePictures("");
				taskExecutionDO.setAiResult(null);
			}
			taskExecutionDO.setSubmitter(
				supplierDealTaskRequest.getSubmitter().concat("(").concat(supplierDealTaskRequest.getSubmitterMobile()).concat(")"));
			taskExecutionDO.setCompletionTime(new Date());
			taskExecutionDO.setDealStatus(1);
			//更新任务信息
			taskExecutionBaseService.updateTaskExecution(taskExecutionDO);
			//异步调用ai大数据模型处理图片
			workOrderAIService.dealWorkOrderAIPhoto(taskExecutionDO, supplierDealTaskRequest.getTakePictures());
			//需要修改工单状态为执行中(根据工单编号+待执行状态查询)
			if (StringUtils.isNotBlank(taskExecutionDO.getWorkOrderNumber())) {
				List<WorkOrderDO> workOrderDOList = workOrderBaseService.selectListByWorkOrderNumber(taskExecutionDO.getWorkOrderNumber());
				if (CollectionUtils.isNotEmpty(workOrderDOList)) {
					WorkOrderDO workOrderDO = workOrderDOList.get(0);
					workOrderDO.setDocumentStatus(StoreWorkOrderStatusEnum.IN_PROGRESS.getType());
					workOrderBaseService.update(workOrderDO);
					//同时修改工单-接单人关联表状态信息
					List<WorkOrderReceiverDO> workOrderReceiverDOList = supplierWorkOrderBaseService.selectListByWorkOrderNumber(taskExecutionDO.getWorkOrderNumber());
					if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
						List<WorkOrderReceiverDO> updateList = new ArrayList<>();
						workOrderReceiverDOList.forEach(workOrderReceiverDO -> {
							workOrderReceiverDO.setDocumentStatus(StoreWorkOrderStatusEnum.IN_PROGRESS.getType());
							updateList.add(workOrderReceiverDO);
						});
						supplierWorkOrderBaseService.updateBatchById(updateList);
					}
				}
			}
			BeanUtils.copyProperties(taskExecutionDO, taskExecutionDetailResponse);
			taskExecutionDetailResponse.setTaskExecutionId(taskExecutionDO.getId());
			if (Objects.nonNull(taskExecutionDetailResponse.getClosingInspection())) {
				taskExecutionDetailResponse.setClosingInspectionValue(
					Objects.requireNonNull(ClosingInspectionEnum.queryByType(taskExecutionDetailResponse.getClosingInspection())).getDesc());
			}
			if (Objects.nonNull(taskExecutionDetailResponse.getNoSuchItemFlag())) {
				taskExecutionDetailResponse.setNoSuchItemFlagValue(
					Objects.requireNonNull(NoSuchItemEnum.queryByType(taskExecutionDetailResponse.getNoSuchItemFlag())).getDesc());
			}
			if (Objects.nonNull(taskExecutionDetailResponse.getDealStatus())) {
				taskExecutionDetailResponse.setDealStatusValue(
					Objects.requireNonNull(TaskDealStatusEnum.queryByType(taskExecutionDetailResponse.getDealStatus())).getDesc());
			}
			//示意图
			if (StringUtils.isNotBlank(taskExecutionDO.getSchematicDrawing())) {
				taskExecutionDetailResponse.setSchematicDrawing(JSONArray.parseArray(taskExecutionDO.getSchematicDrawing(), FileVO.class));
			}
			//处理人员上传的图片
			if (CollectionUtils.isNotEmpty(supplierDealTaskRequest.getTakePictures())) {
				taskExecutionDetailResponse.setTakePictures(supplierDealTaskRequest.getTakePictures());
			}
		}
		return taskExecutionDetailResponse;
	}

	public SupplierTaskDetailResponse getTaskInfo(Long taskExecutionId) {
		SupplierTaskDetailResponse supplierTaskDetailResponse = new SupplierTaskDetailResponse();
		//获取任务信息
		TaskExecutionDO taskExecutionDO = taskExecutionBaseService.getById(taskExecutionId);
		if (Objects.nonNull(taskExecutionDO)) {
			BeanUtils.copyProperties(taskExecutionDO, supplierTaskDetailResponse);
			supplierTaskDetailResponse.setTaskExecutionId(taskExecutionDO.getId());
			//处理图片string->list
			//示意图
			String schematicDrawing = taskExecutionDO.getSchematicDrawing();
			if (StringUtils.isNotBlank(schematicDrawing)) {
				supplierTaskDetailResponse.setSchematicDrawing(JSONArray.parseArray(schematicDrawing, FileVO.class));
			}
			//处理任务的拍照图片
			String takePictures = taskExecutionDO.getTakePictures();
			if (StringUtils.isNotBlank(takePictures)) {
				supplierTaskDetailResponse.setTakePictures(JSONArray.parseArray(takePictures, AiResultVO.class));
			}
			String remarkPicture = taskExecutionDO.getRemarkPicture();
			if (StringUtils.isNotBlank(remarkPicture)) {
				supplierTaskDetailResponse.setRemarkPicture(JSONArray.parseArray(remarkPicture, FileVO.class));
			}
			if (Objects.nonNull(taskExecutionDO.getClosingInspection())) {
				supplierTaskDetailResponse.setClosingInspectionValue(Objects.requireNonNull(ClosingInspectionEnum.queryByType(taskExecutionDO.getClosingInspection())).getDesc());
			}
			if (Objects.nonNull(taskExecutionDO.getNoSuchItemFlag())) {
				supplierTaskDetailResponse.setNoSuchItemFlagValue(Objects.requireNonNull(NoSuchItemEnum.queryByType(taskExecutionDO.getNoSuchItemFlag())).getDesc());
			}
			if (Objects.nonNull(taskExecutionDO.getDealStatus())) {
				supplierTaskDetailResponse.setDealStatusValue(Objects.requireNonNull(TaskDealStatusEnum.queryByType(taskExecutionDO.getDealStatus())).getDesc());
			}
			if (StringUtils.isNotBlank(taskExecutionDO.getEarlyAcceptance())) {
				supplierTaskDetailResponse.setEarlyAcceptanceValue(Objects.requireNonNull(StoreTaskEnum.queryByType(taskExecutionDO.getEarlyAcceptance())).getDesc());
			}
		}
		return supplierTaskDetailResponse;
	}

}
